﻿using Alkitab.Language;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;

namespace Alkitab
{
    public partial class SearchVerse : PhoneApplicationPage
    {
        private BackgroundWorker bw;
        private ObservableCollection<AyatFull> result = new ObservableCollection<AyatFull>();

        public SearchVerse()
        {
            InitializeComponent();
            BuildApplicationBar();
            oldTestamentList.ItemsSource = Globals.daftarBukuA;
            newTestamentList.ItemsSource = Globals.daftarBukuN;

            bw = new BackgroundWorker();
            bw.WorkerSupportsCancellation = true;
            bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(doneSearch);
            bw.DoWork += new DoWorkEventHandler(doSearch);
        }

        public void doneSearch(object sender, RunWorkerCompletedEventArgs e)
        {
            Deployment.Current.Dispatcher.BeginInvoke(delegate
            {
                resultList.ItemsSource = (ObservableCollection<AyatFull>)e.Result;
                progressbar.Visibility = Visibility.Collapsed;
                progressbar.IsIndeterminate = false;
            });
        }

        public void doSearch(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker bw = sender as BackgroundWorker;

            result.Clear();

            List<String> neededInfo = (List<String>)e.Argument;

            bool perjanjianBaru = false;
            bool firstItem = true;

            foreach (String item in neededInfo)
            {
                if (firstItem)
                {
                    firstItem = false;
                }
                else
                    if (item.Equals("-----"))
                    {
                        perjanjianBaru = true;
                        continue;
                    }
                    else
                    {
                        if (perjanjianBaru)
                        {
                            int bookIndex = Globals.daftarBukuN.IndexOf(item) + 39 + 1;
                            foreach (AyatFull ayatFull in getText(bookIndex, neededInfo[0]))
                            {
                                result.Add(ayatFull);
                            }
                        }
                        else
                        {
                            int bookIndex = Globals.daftarBukuA.IndexOf(item) + 1;
                            foreach (AyatFull ayatFull in getText(bookIndex, neededInfo[0]))
                            {
                                result.Add(ayatFull);
                            }
                        }
                    }
            }

            e.Result = result;
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            // do some stuff ...
            bw.CancelAsync();

            // cancel the navigation
            NavigationService.GoBack();
        }

        private void BuildApplicationBar()
        {
            ApplicationBar = new ApplicationBar();

            ApplicationBarIconButton selectAllButton = new ApplicationBarIconButton(new Uri("Images/ApplicationBar/appbar.check.rest.png", UriKind.Relative));
            selectAllButton.Text = Labels.selectAll;
            selectAllButton.Click += new EventHandler(selectAll_Click);
            ApplicationBar.Buttons.Add(selectAllButton);

            ApplicationBarMenuItem selectOldTestament = new ApplicationBarMenuItem(Labels.selectOld);
            selectOldTestament.Click += new EventHandler(selectOld_Click);
            ApplicationBar.MenuItems.Add(selectOldTestament);

            ApplicationBarMenuItem selectNewTestament = new ApplicationBarMenuItem(Labels.selectNew);
            selectNewTestament.Click += new EventHandler(selectNew_Click);
            ApplicationBar.MenuItems.Add(selectNewTestament);
        }

        private T FindParentOfType<T>(DependencyObject element) where T : DependencyObject
        {
            T result = null;
            DependencyObject currentElement = element;
            while (currentElement != null)
            {
                result = currentElement as T;
                if (result != null)
                {
                    break;
                }
                currentElement = VisualTreeHelper.GetParent(currentElement);
            }
            return result;
        }

        private ObservableCollection<AyatFull> getText(int kk, string searchWord)
        {
            ObservableCollection<AyatFull> tmp = new ObservableCollection<AyatFull>();
            tmp.Clear();
            string k = Convert.ToString(kk);
            int x = 0;
            string tmp2 = "";
            bool startRead = false;
            bool endRead = false;
            bool terjemahahanlamakah = false;
            if (kk < 40) terjemahahanlamakah = true;
            int ibuku = kk;
            if (!terjemahahanlamakah) ibuku -= 39;
            bool ayatMazmuzrkah = ((kk == 19) && (Globals.versiKitab.Equals("TerjemahanBaru")));
            char[] delimiterChars = { '\t' };
            String tempxx = "Kitab/" + Globals.versiKitab + "/" + k + ".txt";
            var rs = Application.GetResourceStream(new Uri(tempxx, UriKind.Relative));
            StreamReader inFlow = new StreamReader(rs.Stream);
            while (startRead == false)
            {
                tmp2 = inFlow.ReadLine();

                string[] pecahan = tmp2.Split(delimiterChars);
                startRead = true;
                bool contains = false;
                if (pecahan[4].ToLower().Contains(searchWord.ToLower().Trim()))
                {
                    contains = true;
                }
                if (contains)
                {
                    string ayat = "";
                    if (ayatMazmuzrkah)
                    {
                        ayat = "(" + pecahan[3] + ") " + Alkitab.Bacaan.prosesMazmurAyat(pecahan[4]);
                    }
                    else
                    {
                        ayat = "(" + pecahan[3] + ") " + pecahan[4];
                    }
                    tmp.Add(new AyatFull(terjemahahanlamakah, ibuku, int.Parse(pecahan[2]), int.Parse(pecahan[3]), ayat));
                    Deployment.Current.Dispatcher.BeginInvoke(delegate
                    {
                        resultCount.Text = ((int.Parse(resultCount.Text)) + 1) + "";
                    });
                }
                x++;
            }

            while (endRead == false)
            {
                tmp2 = inFlow.ReadLine();
                if (tmp2 == null) { endRead = true; break; }
                string[] pecahan = tmp2.Split(delimiterChars);
                bool contains = false;
                if (pecahan[4].ToLower().Contains(searchWord.ToLower().Trim()))
                {
                    contains = true;
                }
                if (contains)
                {
                    string ayat = "";
                    if (ayatMazmuzrkah)
                    {
                        ayat = "(" + pecahan[3] + ") " + Alkitab.Bacaan.prosesMazmurAyat(pecahan[4]);
                    }
                    else
                    {
                        ayat = "(" + pecahan[3] + ") " + pecahan[4];
                    }
                    tmp.Add(new AyatFull(terjemahahanlamakah, ibuku, int.Parse(pecahan[2]), int.Parse(pecahan[3]), ayat));
                    Deployment.Current.Dispatcher.BeginInvoke(delegate
                    {
                        resultCount.Text = ((int.Parse(resultCount.Text)) + 1) + "";
                    });
                }
                x++;
            }

            return tmp;
        }

        private void resultList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (resultList.SelectedIndex >= 0)
            {
                Globals.terjemahansblmnya = Globals.terjemahanlamakah;
                Globals.nopasalsblmnya = Globals.nopasal;
                Globals.nobukusblmnya = Globals.nobuku;

                AyatFull ayat = result[resultList.SelectedIndex];
                Globals.terjemahanlamakah = ayat.terjemahanLama;
                Globals.nobuku = ayat.noBuku;
                Globals.nopasal = ayat.noPasal;
                Globals.noayat = ayat.noAyat;

                if ((!(Globals.nobuku == 0)) && (!(Globals.nopasal == 0)))
                {
                    Globals.stopupdatinghistory = true;
                    NavigationService.Navigate(new Uri("/View/Bacaan.xaml", UriKind.Relative));
                    resultList.SelectedIndex = -1;
                }
                else Alkitab.HistoryAndBookmark.showMSGBug();
            }
        }

        private void searchBox_GotFocus(object sender, RoutedEventArgs e)
        {
            if (searchBox.Text == Labels.textBox_InputText)
            {
                searchBox.Text = "";
            }
            SolidColorBrush Brush1 = new SolidColorBrush();
            Brush1.Color = Colors.Black;
            searchBox.Foreground = Brush1;
        }

        private void searchBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                searchBox.Text = searchBox.Text.Trim();
                this.Focus();
            }
        }

        private void searchBox_LostFocus(object sender, RoutedEventArgs e)
        {
            if (searchBox.Text == Labels.textBox_InputText)
            {
                SolidColorBrush Brush2 = new SolidColorBrush();
                Brush2.Color = Colors.Gray;
                searchBox.Foreground = Brush2;
            }
            else
            {
                if (searchBox.Text.Length > 1)
                {
                    progressbar.Visibility = Visibility.Visible;
                    progressbar.IsIndeterminate = true;
                    resultCount.Text = "0";

                    List<String> neededInfo = new List<string>();
                    neededInfo.Add(searchBox.Text);
                    foreach (String item in oldTestamentList.SelectedItems)
                    {
                        neededInfo.Add(item);
                    }
                    neededInfo.Add("-----");
                    foreach (String item in newTestamentList.SelectedItems)
                    {
                        neededInfo.Add(item);
                    }

                    bw.RunWorkerAsync(neededInfo);
                }
            }
        }

        private void selectAll_Click(object sender, EventArgs e)
        {
            if ((newTestamentList.SelectedItems.Count == (newTestamentList.ItemsSource as IList<string>).Count) && (oldTestamentList.SelectedItems.Count == (oldTestamentList.ItemsSource as IList<string>).Count))
            {
                newTestamentList.SelectedItems.Clear();
                oldTestamentList.SelectedItems.Clear();
            }
            else
            {
                foreach (Object obj in newTestamentList.ItemsSource)
                {
                    newTestamentList.SelectedItems.Add(obj);
                }
                foreach (Object obj in oldTestamentList.ItemsSource)
                {
                    oldTestamentList.SelectedItems.Add(obj);
                }
            }
        }

        private void selectNew_Click(object sender, EventArgs e)
        {
            if (newTestamentList.SelectedItems.Count == (newTestamentList.ItemsSource as IList<string>).Count)
            {
                newTestamentList.SelectedItems.Clear();
            }
            else
            {
                foreach (Object obj in newTestamentList.ItemsSource)
                {
                    newTestamentList.SelectedItems.Add(obj);
                }
            }
        }

        private void selectOld_Click(object sender, EventArgs e)
        {
            if (oldTestamentList.SelectedItems.Count == (oldTestamentList.ItemsSource as IList<string>).Count)
            {
                oldTestamentList.SelectedItems.Clear();
            }
            else
            {
                foreach (Object obj in oldTestamentList.ItemsSource)
                {
                    oldTestamentList.SelectedItems.Add(obj);
                }
            }
        }
    }
}